﻿using Microsoft.Extensions.DependencyInjection;
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;

namespace MaximServices.Common
{
    public static class IdFactoryConfigurationExtensions
    {
        public static IServiceCollection UseIdFactory(this IServiceCollection service, IConfiguration configuration)
        {
            service.AddSingleton<IdFactoryOptions>(new IdFactoryOptions(configuration));

            service.AddSingleton<SnowflakeIdWorker>(provider =>
            {
                var idFactoryOptions = provider.GetService<IdFactoryOptions>();

                return new SnowflakeIdWorker(
                        idFactoryOptions.WorkerId,
                        idFactoryOptions.DataCenterId
                 );

            });

            return service;
        }
    }

    public class IdFactoryOptions
    {
        public IdFactoryOptions(IConfiguration configuration)
        {
            WorkerId = 1;
            DataCenterId = 1;

            if (null != configuration)
            {
                var workerIdString = configuration["IdFactory:WorkerId"];
                var dataCenterIdString = configuration["IdFactory:DataCenterId"];

                if (!string.IsNullOrWhiteSpace(workerIdString))
                {
                    WorkerId = Convert.ToInt64(workerIdString);
                }

                if (!string.IsNullOrWhiteSpace(dataCenterIdString))
                {
                    DataCenterId = Convert.ToInt64(dataCenterIdString);
                }
            }
        }

        public long WorkerId { get; set; }
        public long DataCenterId { get; set; }
    }
}
